// com.example.aftersales.service.impl.UserServiceImpl.java
package com.example.aftersales.service.impl;

import com.example.aftersales.entity.User;
import com.example.aftersales.mapper.UserMapper;
import com.example.aftersales.service.UserService;
import com.example.aftersales.vo.ServiceResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public ServiceResult<Boolean> register(String username, String password, String role) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(username);
        if (existingUser != null) {
            return ServiceResult.fail("用户名已存在");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 明文存储
        user.setRole(role);

        int result = userMapper.insert(user);
        if (result > 0) {
            return ServiceResult.success(true, "注册成功");
        } else {
            return ServiceResult.fail("注册失败");
        }
    }

    @Override
    public ServiceResult<User> login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return ServiceResult.fail("用户名不存在");
        }

        if (!user.getPassword().equals(password)) {
            return ServiceResult.fail("密码错误");
        }

        return ServiceResult.success(user, "登录成功");
    }

    @Override
    @Transactional
    public ServiceResult<Boolean> updateProfile(String username, String newPassword) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return ServiceResult.fail("用户不存在");
        }

        // 只有提供了新密码才更新
        if (newPassword != null && !newPassword.isEmpty()) {
            user.setPassword(newPassword);
        }

        int result = userMapper.updateProfile(username, user.getPassword());
        if (result > 0) {
            return ServiceResult.success(true, "个人信息更新成功");
        } else {
            return ServiceResult.fail("更新失败");
        }
    }

    @Override
    public User getByUsername(String username) {
        return userMapper.findByUsername(username);
    }
}